<template>
  <div class="login_wrap">
    <img class="top_img" src="@/assets/images/top.png" alt="" />
    <div class="form_wrap">
      <img class="left_button" src="@/assets/images/logo.png" alt="" />
      <div class="input_wrap">
        <van-field
          required
          clearable
          v-model="userForm.uname"
          placeholder="请输入用户名"
        />
        <van-field
          type="password"
          v-model="userForm.password"
          placeholder="请输入密码"
        />
      </div>
      <van-button
        v-show="!loginStatue"
        class="login_btn"
        type="primary"
        @click="handleLogin"
        >登录</van-button
      >
      <van-button
        v-show="loginStatue"
        class="login_btn"
        type="primary"
        @click="handleRegister"
        >注册</van-button
      >
      <p class="button_info">
        <span @click="handleChangeStatue">{{
          loginStatue ? "去登陆" : "去注册"
        }}</span>
      </p>
    </div>
  </div>
</template>

<script lang='ts'>
//interface
import { LoginUser } from "../entity/user";

//api
import { login, register } from "../api/user";

import { Options, Vue } from "vue-class-component";
import { R } from "@/entity/R";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

@Options({
  components: {},
})
export default class Login extends Vue {
  //用户登录
  userForm: LoginUser = {};
  //双改状态
  loginStatue: boolean = false;
  handleChangeStatue = () => {
    this.loginStatue = !this.loginStatue;
  };

  //登录按钮
  dataOfToken: R = {};

  router = useRouter();
  store = useStore();
  public handleLogin = async () => {
    let data = await login(
      this.userForm.uname || "0",
      this.userForm.password || ""
    );
    console.log("data数据是", data);
    if (data.code == 2000) {
      //如果等于2000  则开始获取token 存入本地缓存
      localStorage.setItem("token", data.data.token);
      this.store.commit("userInfo/setToken", data.data.token);
      this.router.push("/");
    } else {
      showToast(data.message);
    }
  };

  //注册接口
  handleRegister = async () => {
    let registerDate = await register(
      this.userForm.uname || "",
      this.userForm.password || ""
    );
    if (registerDate.code == 2000) {
      showToast(registerDate.message);
      //修改状态
      this.loginStatue = !this.loginStatue;
    } else {
      showToast(registerDate.message);
      this.userForm.uname = "";
      this.userForm.password = "";
    }
  };
}
</script>

<style lang='less' scoped>
@import url("@/assets/less/login.less");
</style> 